// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.TransactionReportReconciliation;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.ShopInfoMapper;
import com.fowo.api.mapper.SysRegionMapper;
import com.fowo.api.mapper.TransactionReportReconciliationMapper;
import com.fowo.api.model.shop.info.ShopInfoItemVo;
import com.fowo.api.model.shop.info.ShopInfoSearchParamPo;
import com.fowo.api.model.sys.region.SysRegionItemVo;
import com.fowo.api.model.sys.region.SysRegionSearchParamPo;
import com.fowo.api.model.transaction.report.reconciliation.TransactionReportReconciliationConfirmReconciliationAction;
import com.fowo.api.model.transaction.report.reconciliation.TransactionReportReconciliationExcelPo;
import com.fowo.api.model.transaction.report.reconciliation.TransactionReportReconciliationImportPo;
import com.fowo.api.model.transaction.report.reconciliation.TransactionReportReconciliationItemVo;
import com.fowo.api.model.transaction.report.reconciliation.TransactionReportReconciliationSearchParamPo;
import com.fowo.api.model.transaction.report.reconciliation.TransactionReportReconciliationVo;
import com.fowo.api.service.TransactionReportReconciliationService;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 交易报告对账 服务实现类
 * @author 蜂窝蜜造平台 配置人：尹建栋，王阳阳
 */
@Service
@Slf4j
@DataObjectType(TransactionReportReconciliation.class)
@DS("ds24")
public class TransactionReportReconciliationServiceImpl
  extends ServiceImpl<TransactionReportReconciliationMapper, TransactionReportReconciliation>
  implements TransactionReportReconciliationService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("storeShopName", "si.`shop_name`");
      put("stationName", "sr.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected TransactionReportReconciliationService self;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected ShopInfoMapper shopInfoMapper;

  @Resource
  protected SysRegionMapper sysRegionMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected TransactionReportReconciliationConfirmReconciliationAction transactionReportReconciliationConfirmReconciliationAction;

  @Resource
  protected Validator validator;

  /**
   * 创建交易报告对账
   * @param model 交易报告对账
   * @return 新数据的主键
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(TransactionReportReconciliationVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    TransactionReportReconciliation entity =
      new TransactionReportReconciliation();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.save(entity)) {
      return entity.getId();
    }
    throw new Exception("交易报告对账保存失败");
  }

  /**
   * 更新交易报告对账
   * @param model 交易报告对账
   * @return 更新是否成功
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(TransactionReportReconciliationVo model)
    throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    TransactionReportReconciliation entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("交易报告对账不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      return true;
    }
    return false;
  }/**
   * 更新交易报告对账（带空值）
   * @param model 交易报告对账
   * @return 更新是否成功
   */

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(TransactionReportReconciliationVo model)
    throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    TransactionReportReconciliation entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("交易报告对账不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(TransactionReportReconciliation::getStore, model.getStore())
      .set(TransactionReportReconciliation::getStation, model.getStation())
      .set(
        TransactionReportReconciliation::getReportType,
        model.getReportType()
      )
      .set(
        TransactionReportReconciliation::getLastUpdateTime,
        model.getLastUpdateTime()
      )
      .set(
        TransactionReportReconciliation::getLastUpdateUser,
        model.getLastUpdateUser()
      )
      .set(
        TransactionReportReconciliation::getReportingInterval,
        model.getReportingInterval()
      )
      .set(
        TransactionReportReconciliation::getReconciliationResults,
        model.getReconciliationResults()
      )
      .set(
        TransactionReportReconciliation::getCurrencyType,
        model.getCurrencyType()
      )
      .set(
        TransactionReportReconciliation::getSubtotalOfDifferences,
        model.getSubtotalOfDifferences()
      )
      .set(
        TransactionReportReconciliation::getAnalysisOfReasonsForDifferences,
        model.getAnalysisOfReasonsForDifferences()
      )
      .set(TransactionReportReconciliation::getRevenue, model.getRevenue())
      .set(
        TransactionReportReconciliation::getDifference,
        model.getDifference()
      )
      .set(
        TransactionReportReconciliation::getExpenditure,
        model.getExpenditure()
      )
      .set(
        TransactionReportReconciliation::getTaxesAndFees,
        model.getTaxesAndFees()
      )
      .set(TransactionReportReconciliation::getTransfer, model.getTransfer())
      .eq(TransactionReportReconciliation::getId, model.getId())
      .update();
    if (isOk) {}
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(
    TransactionReportReconciliationSearchParamPo search
  ) {
    return false;
  }

  /**
   * 删除交易报告对账
   * @param id 交易报告对账的主键
   * @return 删除是否成功
   */
  @Override
  public boolean delete(Long id) throws Exception {
    return this.removeById(id);
  }

  /**
   * 批量删除交易报告对账
   * @param ids 交易报告对账的主键列表
   * @return 删除是否成功
   */
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<TransactionReportReconciliationImportPo> excelToImportRow(
    TransactionReportReconciliationImportPo row,
    Integer rowNumber,
    TransactionReportReconciliationVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<TransactionReportReconciliationImportPo> ir =
      new ImportRow<TransactionReportReconciliationImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<TransactionReportReconciliationImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new TransactionReportReconciliationVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, TransactionReportReconciliationImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getReportType())) {
      List<SysDictAllItem> reportTypeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "reportType",
          n -> sysDictService.getDictItems(" SCM00233")
        );
      TransactionReportReconciliationVo finalVo = vo;
      reportTypeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getReportType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setReportType(i.getItemValue()),
          () ->
            ir.addError(
              "reportType",
              String.format(
                "必须为 %s 中之一",
                reportTypeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getReconciliationResults())) {
      List<SysDictAllItem> reconciliationResultsItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "reconciliationResults",
          n -> sysDictService.getDictItems("SCM00219")
        );
      TransactionReportReconciliationVo finalVo = vo;
      reconciliationResultsItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getReconciliationResults()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setReconciliationResults(i.getItemValue()),
          () ->
            ir.addError(
              "reconciliationResults",
              String.format(
                "必须为 %s 中之一",
                reconciliationResultsItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setSubtotalOfDifferences(
      SheetUtils.tryToDecimal(row.getSubtotalOfDifferences())
    );
    vo.setRevenue(SheetUtils.tryToDecimal(row.getRevenue()));
    if (StringUtils.hasText(row.getDifference())) {
      List<SysDictAllItem> differenceItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "difference",
          n -> sysDictService.getDictItems(" SCM00221")
        );
      TransactionReportReconciliationVo finalVo = vo;
      differenceItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getDifference()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setDifference(i.getItemValue()),
          () ->
            ir.addError(
              "difference",
              String.format(
                "必须为 %s 中之一",
                differenceItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setExpenditure(SheetUtils.tryToDecimal(row.getExpenditure()));
    vo.setTaxesAndFees(SheetUtils.tryToDecimal(row.getTaxesAndFees()));
    vo.setTransfer(SheetUtils.tryToDecimal(row.getTransfer()));
    // 处理关联字段“店铺”
    if (
      !SheetUtils.isBlank(row.getStoreShopName()) &&
      SheetUtils.isBlank(row.getStore())
    ) {
      ShopInfoSearchParamPo storeSearchParam = new ShopInfoSearchParamPo();
      storeSearchParam.setLimit(2); // 最大只返回二行记录
      storeSearchParam.setShopNameEq(SheetUtils.trim(row.getStoreShopName()));
      storeSearchParam.applySqlSegments();
      List<ShopInfoItemVo> storeMatches = shopInfoMapper.search(
        storeSearchParam
      );
      if (storeMatches.size() == 0) {
        ir.addError("storeShopName", "未能在店铺中找到匹配的数据");
      } else if (storeMatches.size() > 1) {
        ir.addError("storeShopName", "关联不唯一，在店铺中找到多个匹配的数据");
      } else {
        vo.setStore(storeMatches.get(0).getId());
      }
    }
    // 处理关联字段“国家”
    if (
      !SheetUtils.isBlank(row.getStationName()) &&
      SheetUtils.isBlank(row.getStation())
    ) {
      SysRegionSearchParamPo stationSearchParam = new SysRegionSearchParamPo();
      stationSearchParam.setLimit(2); // 最大只返回二行记录
      stationSearchParam.setNameEq(SheetUtils.trim(row.getStationName()));
      stationSearchParam.applySqlSegments();
      List<SysRegionItemVo> stationMatches = sysRegionMapper.search(
        stationSearchParam
      );
      if (stationMatches.size() == 0) {
        ir.addError("stationName", "未能在站点中找到匹配的数据");
      } else if (stationMatches.size() > 1) {
        ir.addError("stationName", "关联不唯一，在站点中找到多个匹配的数据");
      } else {
        vo.setStation(stationMatches.get(0).getId());
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<TransactionReportReconciliationImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<TransactionReportReconciliationImportPo>> rows =
        new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            TransactionReportReconciliationImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              TransactionReportReconciliationImportPo row,
              AnalysisContext cxt
            ) {
              TransactionReportReconciliationVo vo =
                new TransactionReportReconciliationVo();
              ImportRow<TransactionReportReconciliationImportPo> ir =
                excelToImportRow(
                  row,
                  cxt.readRowHolder().getRowIndex(),
                  vo,
                  variables,
                  allowOverrides
                );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<TransactionReportReconciliationImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<TransactionReportReconciliationImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      TransactionReportReconciliationVo vo =
        new TransactionReportReconciliationVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @Override
  public void export(
    Long templateId,
    TransactionReportReconciliationSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "store",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((TransactionReportReconciliationItemVo) r).getStoreShopName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "reconciliationResults",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00219")
      );
      exportOptions.addFieldMappingOption(
        "difference",
        new CustomExcelExport.FieldMappingOption().setDictCode(" SCM00221")
      );
      exportOptions.addStringFields(
        "storeShopName",
        "reportingInterval",
        "reconciliationResults",
        "currencyType",
        "analysisOfReasonsForDifferences",
        "difference"
      );

      String fileName = String.format(
        "交易报告对账(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> reconciliationResultsItems =
      sysDictService.getDictItems("SCM00219");
    List<SysDictAllItem> differenceItems = sysDictService.getDictItems(
      " SCM00221"
    );
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<TransactionReportReconciliationExcelPo> items =
      new ArrayList<TransactionReportReconciliationExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<TransactionReportReconciliationItemVo> page =
        this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<TransactionReportReconciliationItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (TransactionReportReconciliationItemVo item : list) {
        TransactionReportReconciliationExcelPo excel =
          new TransactionReportReconciliationExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getReconciliationResults() != null) {
          reconciliationResultsItems
            .stream()
            .filter(i ->
              i.getItemValue().equals(item.getReconciliationResults())
            )
            .findFirst()
            .ifPresent(i -> excel.setReconciliationResults(i.getItemText()));
        }
        if (item.getDifference() != null) {
          differenceItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getDifference()))
            .findFirst()
            .ifPresent(i -> excel.setDifference(i.getItemText()));
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "交易报告对账(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(TransactionReportReconciliationExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过报告区间查询交易报告对账主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByReportingInterval(String reportingInterval) {
    return this.baseMapper.getIdByReportingInterval(reportingInterval);
  }

  /**
   * 通过报告区间查询交易报告对账多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByReportingInterval(List<String> list) {
    return this.baseMapper.getIdsByReportingInterval(list);
  }

  /**
   * 通过交易报告对账主键查询报告区间
   */
  @Override
  public String getReportingIntervalById(Long id) {
    return this.baseMapper.getReportingIntervalById(id);
  }

  /**
   * 通过交易报告对账主键查询报告区间列表
   */
  @Override
  public List<String> getReportingIntervalByIds(List<Long> ids) {
    List<Map<String, Object>> maps =
      this.baseMapper.getReportingIntervalByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap ->
            (String) stringObjectMap.get("reportingInterval")
          )
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 交易报告对账的主键
   */
  @Override
  public TransactionReportReconciliationVo getVoById(Long id) throws Exception {
    TransactionReportReconciliationVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }
    return vo;
  }

  /**
   * 分页查询交易报告对账
   * @param search 查询条件
   * @return 交易报告对账分页查询结果
   */
  @Override
  public Page<TransactionReportReconciliationItemVo> pageSearch(
    TransactionReportReconciliationSearchParamPo search
  ) {
    Page<TransactionReportReconciliationItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(TransactionReportReconciliationItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 交易报告对账快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'TransactionReportReconciliationOptions::' + #search.keyword"
  )
  public List<OptionItem<TransactionReportReconciliationItemVo>> searchOptions(
    TransactionReportReconciliationSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询交易报告对账
   * @param search 查询条件
   * @return 交易报告对账列表查询结果
   */
  @Override
  public List<TransactionReportReconciliationItemVo> search(
    TransactionReportReconciliationSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询交易报告对账最后更新时间
   * @param search 查询条件
   * @return 交易报告对账最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(
    TransactionReportReconciliationSearchParamPo search
  ) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 确认对账
   */
  @Override
  public void confirmReconciliation(List<Long> ids) throws Exception {
    if (transactionReportReconciliationConfirmReconciliationAction == null) {
      throw new Exception("此操作当前不可用");
    }
    transactionReportReconciliationConfirmReconciliationAction.run(ids);
  }

  /**
   * 全部
   */
  @Override
  public List<TransactionReportReconciliationItemVo> allType(
    TransactionReportReconciliationSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.allType(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<TransactionReportReconciliationItemVo> allTypePage(
    TransactionReportReconciliationSearchParamPo search
  ) {
    Page<TransactionReportReconciliationItemVo> allTypePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return allTypePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return allTypePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    allTypePage =
      this.baseMapper.allTypePage(
          search.toPage(this.baseMapper.allTypeCount(search)),
          search
        );
    List<Long> recordIds = allTypePage
      .getRecords()
      .stream()
      .map(TransactionReportReconciliationItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return allTypePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return allTypePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    allTypePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return allTypePage;
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date allTypeLastUpdateTime(
    TransactionReportReconciliationSearchParamPo search
  ) {
    return this.baseMapper.allTypeLastUpdateTime(search);
  }

  /**
   * 无差异
   */
  @Override
  public List<TransactionReportReconciliationItemVo> noDifferent(
    TransactionReportReconciliationSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.noDifferent(search);
  }

  /**
   * 无差异分页
   */
  @Override
  public Page<TransactionReportReconciliationItemVo> noDifferentPage(
    TransactionReportReconciliationSearchParamPo search
  ) {
    Page<TransactionReportReconciliationItemVo> noDifferentPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return noDifferentPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return noDifferentPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    noDifferentPage =
      this.baseMapper.noDifferentPage(
          search.toPage(this.baseMapper.noDifferentCount(search)),
          search
        );
    List<Long> recordIds = noDifferentPage
      .getRecords()
      .stream()
      .map(TransactionReportReconciliationItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return noDifferentPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return noDifferentPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    noDifferentPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return noDifferentPage;
  }

  /**
   * 查询无差异最后更新时间
   * @param search 查询条件
   * @return 无差异最后更新时间
   */
  @Override
  public Date noDifferentLastUpdateTime(
    TransactionReportReconciliationSearchParamPo search
  ) {
    return this.baseMapper.noDifferentLastUpdateTime(search);
  }

  /**
   * 有差异
   */
  @Override
  public List<TransactionReportReconciliationItemVo> haveDifferent(
    TransactionReportReconciliationSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.haveDifferent(search);
  }

  /**
   * 有差异分页
   */
  @Override
  public Page<TransactionReportReconciliationItemVo> haveDifferentPage(
    TransactionReportReconciliationSearchParamPo search
  ) {
    Page<TransactionReportReconciliationItemVo> haveDifferentPage =
      new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return haveDifferentPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return haveDifferentPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    haveDifferentPage =
      this.baseMapper.haveDifferentPage(
          search.toPage(this.baseMapper.haveDifferentCount(search)),
          search
        );
    List<Long> recordIds = haveDifferentPage
      .getRecords()
      .stream()
      .map(TransactionReportReconciliationItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return haveDifferentPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return haveDifferentPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    haveDifferentPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return haveDifferentPage;
  }

  /**
   * 查询有差异最后更新时间
   * @param search 查询条件
   * @return 有差异最后更新时间
   */
  @Override
  public Date haveDifferentLastUpdateTime(
    TransactionReportReconciliationSearchParamPo search
  ) {
    return this.baseMapper.haveDifferentLastUpdateTime(search);
  }
}
